package com.secsbrain.engine.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.secsbrain.engine.biz.constant.EnumDefinition;
import com.secsbrain.engine.biz.utils.ParseDtoUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RestController;

import com.secsbrain.common.ErrorCodeEnum;
import com.secsbrain.common.ResponseVo;
import com.secsbrain.engine.client.iface.TaskInfoService;
import com.secsbrain.engine.client.model.HistoryTask;
import com.secsbrain.engine.client.model.TaskDto;

/**
 * 任务相关控制层
 * @author zhaoyi
 *
 */
@RestController
@EnableEurekaClient
public class TaskController implements TaskInfoService{
	
    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);

	@Autowired
	private TaskService taskService;
	
	@Autowired
	private HistoryService historyService;
    
    /**
     * 功能描述: <br>
     * 查询用户要处理的任务
     *
     * @param userId   用户ID
     * @param roleCode 角色编号
     * @return
     */
    @Override
    public ResponseVo<List<TaskDto>> queryTodo(String userId,String roleCode,String... processDefinitionKeys) {
    	Assert.hasText(userId, "用户ID不能为空");
        Assert.hasText(roleCode, "角色编号不能为空");
        
        //区分processDefinitionKey
        
        logger.debug("查询用户要处理的任务。。。userId:{},roleCode:{}",userId,roleCode);
    	
    	List<Task> taskList=new ArrayList<Task>();
    	
    	TaskQuery roleQuery=taskService.createTaskQuery()
                .taskAssignee(roleCode);
    	if(processDefinitionKeys!=null&&processDefinitionKeys.length>0){
    		roleQuery.processDefinitionKeyIn(Arrays.asList(processDefinitionKeys));
    	}
    	taskList.addAll(roleQuery.list());
    	
    	TaskQuery userQuery=taskService.createTaskQuery()
                .taskAssignee(userId);
    	if(processDefinitionKeys!=null&&processDefinitionKeys.length>0){
    		userQuery.processDefinitionKeyIn(Arrays.asList(processDefinitionKeys));
    	}
    	taskList.addAll(userQuery.list());//获取该办理人下的事务列表
    	
    	List<Task> newTaskList=new ArrayList<Task>();
    	for(Task task:taskList){
    		if(task.getCategory()==null){
    			//如果这个标识不为空，说明是被打回的
    			newTaskList.add(task);
    		}
    	}
    	
    	List<TaskDto> list= ParseDtoUtil.parseTaskList(newTaskList);
    	
    	return ResponseVo.getSuccessResponse(list.size(),list);
    }
    
	@Override
	public ResponseVo<List<TaskDto>> queryRefused(String userId,String... processDefinitionKeys) {
		Assert.hasText(userId, "用户ID不能为空");
        
        logger.debug("查询被打回的任务。。。userId:{}",userId);

    	List<Task> taskList=new ArrayList<Task>();
    	TaskQuery userQuery=taskService.createTaskQuery()
                .taskAssignee(userId)
                .taskCategory(EnumDefinition.ApprovalStatus.REFUSE.getCode()+"");
    	if(processDefinitionKeys!=null&&processDefinitionKeys.length>0){
    		userQuery.processDefinitionKeyIn(Arrays.asList(processDefinitionKeys));
    	}
    	taskList.addAll(userQuery.list());
    	
    	List<TaskDto> list=ParseDtoUtil.parseTaskList(taskList);
    	return ResponseVo.getSuccessResponse(list.size(),list);
	}
    
    /**
     * 功能描述: <br>
     * 通过流程实例ID查询当前任务
     *
     * @param processInstanceId  流程实例ID
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public ResponseVo<TaskDto> queryByProcessInstanceId(String processInstanceId){
    	Assert.hasText(processInstanceId, "流程实例ID不能为空");
    	
    	Task newTask =taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    	if(newTask==null){
    		return ErrorCodeEnum.ERROR_COMMON_CHECK.getResponseVo("流程不存在或任务已结束");

    	}
    	return ResponseVo.getSuccessResponse(ParseDtoUtil.parseTask(newTask));
    }
    
    /**
     * 功能描述: <br>
     * 通过实例ID查询流程历史
     *
     * @param processInstanceId  流程实例ID
     * @return
     */
    @Override
    public ResponseVo<List<HistoryTask>> historyByInstanceId(String processInstanceId){
    	List<HistoricActivityInstance> historicActivityInstances = historyService// 创建历史活动实例查询
        .createHistoricActivityInstanceQuery().processInstanceId(processInstanceId)
        .orderByHistoricActivityInstanceStartTime()
        .asc()
        .list();
    	
    	List<HistoryTask> list=ParseDtoUtil.parseHistoryList(historicActivityInstances);
		return ResponseVo.getSuccessResponse(list.size(),list);
    }

    //TODO  指定任务人、已办理的任务
    
}
